import { io } from 'socket.io-client'
import { useGameStore } from '../stores/game'

class SocketService {
  constructor() {
    this.socket = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectDelay = 1000
  }

  // 获取游戏状态存储（延迟初始化）
  get gameStore() {
    try {
      return useGameStore()
    } catch (error) {
      console.warn('Pinia store not available yet:', error)
      return null
    }
  }

  // 连接到服务器
  connect(roomCode, playerId) {
    if (this.socket) {
      this.disconnect()
    }

    if (this.gameStore) {
      this.gameStore.setConnectionStatus('connecting')
    }

    // 创建Socket连接
    this.socket = io(import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000', {
      transports: ['websocket', 'polling'],
      query: {
        roomCode,
        playerId
      }
    })

    this.setupEventListeners()
  }

  // 设置事件监听器
  setupEventListeners() {
    if (!this.socket) return

    // 连接成功
    this.socket.on('connect', () => {
      console.log('Socket connected:', this.socket.id)
      if (this.gameStore) {
        this.gameStore.setConnectionStatus('connected')
      }
      this.reconnectAttempts = 0
    })

    // 连接断开
    this.socket.on('disconnect', (reason) => {
      console.log('Socket disconnected:', reason)
      if (this.gameStore) {
        this.gameStore.setConnectionStatus('disconnected')
      }

      // 自动重连
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        setTimeout(() => {
          this.reconnectAttempts++
          this.socket.connect()
        }, this.reconnectDelay * this.reconnectAttempts)
      }
    })

    // 连接错误
    this.socket.on('connect_error', (error) => {
      console.error('Socket connection error:', error)
      if (this.gameStore) {
        this.gameStore.setConnectionStatus('disconnected')
        this.gameStore.setErrorMessage('连接服务器失败')
      }
    })

    // 游戏事件监听
    this.socket.on('PlayerJoined', this.handlePlayerJoined.bind(this))
    this.socket.on('PlayerLeft', this.handlePlayerLeft.bind(this))
    this.socket.on('GameStarted', this.handleGameStarted.bind(this))
    this.socket.on('GameEnded', this.handleGameEnded.bind(this))
    this.socket.on('PaintActionReceived', this.handlePaintActionReceived.bind(this))
    this.socket.on('AreaUpdated', this.handleAreaUpdated.bind(this))
    this.socket.on('TimerUpdate', this.handleTimerUpdate.bind(this))
    this.socket.on('RoomStateUpdate', this.handleRoomStateUpdate.bind(this))
    this.socket.on('Error', this.handleError.bind(this))
  }

  // 断开连接
  disconnect() {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
    }
    if (this.gameStore) {
      this.gameStore.setConnectionStatus('disconnected')
    }
  }

  // 加入房间
  joinRoom(roomCode, playerInfo) {
    if (!this.socket) return

    this.socket.emit('JoinRoom', {
      roomCode,
      playerId: playerInfo.id,
      nickname: playerInfo.nickname
    })
  }

  // 离开房间
  leaveRoom() {
    if (!this.socket) return

    this.socket.emit('LeaveRoom')
    this.disconnect()
  }

  // 开始游戏
  startGame() {
    if (!this.socket) return

    this.socket.emit('StartGame')
  }

  // 发送涂色动作
  sendPaintAction(paintData) {
    if (!this.socket) return

    this.socket.emit('PaintAction', {
      ...paintData,
      timestamp: Date.now()
    })
  }

  // 重新开始游戏
  restartGame() {
    if (!this.socket) return

    this.socket.emit('RestartGame')
  }

  // 事件处理器
  handlePlayerJoined(playerInfo) {
    console.log('Player joined:', playerInfo)
    if (this.gameStore) {
      this.gameStore.addPlayer(playerInfo)
    }
  }

  handlePlayerLeft(playerId) {
    console.log('Player left:', playerId)
    if (this.gameStore) {
      this.gameStore.removePlayer(playerId)
    }
  }

  handleGameStarted(gameInfo) {
    console.log('Game started:', gameInfo)
    if (this.gameStore) {
      this.gameStore.setGameStatus('playing')
      this.gameStore.setRemainingTime(gameInfo.duration)
      this.gameStore.setPlayers(gameInfo.players)
    }
  }

  handleGameEnded(gameResult) {
    console.log('Game ended:', gameResult)
    if (this.gameStore) {
      this.gameStore.setGameStatus('finished')
      this.gameStore.setPlayers(gameResult.players)
    }
  }

  handlePaintActionReceived(paintData) {
    console.log('Paint action received:', paintData)
    // 这里会触发Canvas组件的远程绘制
    // 通过事件总线或直接调用Canvas方法
    window.dispatchEvent(new CustomEvent('remotePaintAction', {
      detail: paintData
    }))
  }

  handleAreaUpdated(areaData) {
    console.log('Area updated:', areaData)
    // 更新玩家面积
    if (this.gameStore) {
      areaData.areas.forEach(({ playerId, area }) => {
        this.gameStore.updatePlayerArea(playerId, area)
      })
    }
  }

  handleTimerUpdate(timeLeft) {
    console.log('Timer update:', timeLeft)
    if (this.gameStore) {
      this.gameStore.setRemainingTime(timeLeft)
    }
  }

  handleRoomStateUpdate(roomState) {
    console.log('Room state update:', roomState)
    if (this.gameStore) {
      this.gameStore.setCurrentRoom(roomState.room)
      this.gameStore.setPlayers(roomState.players)
      this.gameStore.setGameStatus(roomState.status)
      if (roomState.remainingTime !== undefined) {
        this.gameStore.setRemainingTime(roomState.remainingTime)
      }
      if (roomState.gameDuration !== undefined) {
        this.gameStore.setGameDuration(roomState.gameDuration)
      }
    }
  }

  handleError(error) {
    console.error('Socket error:', error)
    if (this.gameStore) {
      this.gameStore.setErrorMessage(error.message || '发生未知错误')
    }
  }

  // 获取连接状态
  isConnected() {
    return this.socket && this.socket.connected
  }

  // 获取Socket实例
  getSocket() {
    return this.socket
  }
}

// 创建单例实例
const socketService = new SocketService()

export default socketService
